var comPageNum = 1;
var firstScenarioData = {}
var firstClassId = '';
getLableList();
function getLableList(){
    $.ajax({
        type: "GET",
        url: root.goodsInter.listLableByType+"?lableLevel=1&&platformType=20",
        dataType: 'json',
        cache: false,
        success: function (data, status, response) {
            if(data.errorCode == "0") {
                firstScenarioData = data.data;
                var optionStr = '<option value="" selected>---请选择---</option>';
                for (var i=0;i<data.data.length;i++){
                    optionStr+='<option value="'+data.data[i].lable_id+'" >'+data.data[i].lable_name+'</option>';
                }
                $(".first-Scenario").html(optionStr);
            } else {
                layer.msg(data.msg, {
                    icon: 5,
                    time: 1000
                }, function() {

                })
            }
        },
        error: function (xhr, type, errorThrown) {

        }
    });
}
function getSubLableList(el){
    var params = {
        lable_id:el.value
    }
    var succCallBack = function(data, status, response) {
        if(data.errorCode == "0") {
            var optionStr = '<option value="" selected>---请选择---</option>';
            for (var i=0;i<data.data.length;i++){
                optionStr+='<option value="'+data.data[i].lable_id+'" >'+data.data[i].lable_name+'</option>';
            }
            $(".second-Scenario").html(optionStr);
        } else {
            layer.msg(data.msg, {
                icon: 5,
                time: 1000
            }, function() {

            })
        }
    };
    return web.doAjax(root.goodsInter.goods_listSubLable, 'post', params, succCallBack,2);
}
/*日期初始化*/
timeSet("#timemin","#timemax","YYYY-MM-DD hh:mm:ss");
/*表单校验查询*/
$("#form-search").Validform({
    tiptype: 2,
    callback: function (form) {
        comPageNum = 1
        getScenarioData(comPageNum);
        return false;
    }
});

/*场景列表数据获取*/
function getScenarioData(pageNum) {
    var params = {
        pageNum: pageNum,
        pageSize: 10,
        parentId:"",
        sceneId: $(".first-Scenario").val(),
        subSceneId: $(".second-Scenario").val(),
        sceneTitle: $(".scenarioPurchasing").val(),
        startTime: $("#timemin").val(),
        endTime: $("#timemax").val(),
    }
    var succCallBack = function(data, status, response) {
        if(data.errorCode == "0") {
            renderTable(data.data);
            comPageNum = data.data.pageNumber;
            $('.M-box3').pagination({
                pageCount: data.data.totalPage,
                current: comPageNum,
                count: 3,
                isHide: false,
                coping: true,
                jump: true,
                callback: function (api) {
                    var currentPage = api.getCurrent();
                    getScenarioData(currentPage);
                }
            });
        } else {
            layer.msg(data.msg, {
                icon: 5,
                time: 1000
            }, function() {

            })
        }
        power();
    };
    return web.doAjax(root.scenario.queryAppScene, 'post', params, succCallBack,2);
}
/*场景列表数据渲染*/
var dataSource = [];//table的数据源
function renderTable(data) {
    if(dataSource.length>0){
        dataSource.splice(0, dataSource.length); //清空数组
    }
    var dataIndex = 1
    if(data.result!=null){
        $.each(data.result, function(i, field) {
            var rowData = new Array();
            rowData.push(dataIndex++);//序号
            rowData.push(field.sceneIndex);//配置顺序
            rowData.push(field.sceneTitle)//标题
            rowData.push(field.effectTime);//生效时间
            rowData.push(field.expiredTime);//失效时间
            rowData.push(field.creatorName);//创建人
            rowData.push(field.createTime);//创建时间
            rowData.push(field);//数据item
            dataSource.push(rowData);
        });
    }
    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50, 25, 10, 5],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = dealNull(row[3]);
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = dealNull(row[4]);
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = dealNull(row[6]);
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = "<input type='button' class='btn btn-secondary radius size-MINI ml-5' value='编辑' onclick='editScenarioFn(this,\"edit\","+JSON.stringify(row[7])+")'><input type='button' class='btn btn-secondary radius size-MINI ml-5' value='删除' onclick='deleteDataFn("+row[7].id+")'><input type='button' class='btn btn-secondary radius size-MINI ml-5' value='子级场景' onclick='childScenarioFn("+row[7].id+","+row[7].sceneId+")'>";
                        return val;
                    },
                    "targets": 7
                },
            ],
        });
        //权限控制函数
        power();
    }
}
/*场景新增、场景编辑弹框*/
var dataInEditing = {}
function editScenarioFn(el,operateType,editData) {
    dataInEditing = editData;
    var index = layer.open({
        type: 2,
        title: "新增场景",
        area: ["1000px", "650px"],
        offset: '100px',
        content: "sceneAdd.html?operateType="+operateType
    });
}
/*子级场景跳转函数*/
function childScenarioFn(id,firstClassId) {
    var index = layer.open({
        type: 2,
        title: "子级场景",
        content: "secondSceneEditList.html?parentId="+id+'&firstClassId='+firstClassId
    });
    layer.full(index);
}
/*删除场景*/
function deleteDataFn(deleteId) {
    layer.confirm('确认要删除吗？', {
        offset: '300px'
    },function(index) {
        var params = {
            id: deleteId
        }
        var succCallBack = function(data, status, response) {
            console.log(data)
            if(data.errorCode == "0") {
                layer.msg("删除成功", {
                    icon: 6,
                    time: 1000
                }, function() {
                    getScenarioData(1);
                })
            } else {
                layer.msg(data.errorMessage, {
                    icon: 5,
                    time: 1000
                }, function() {

                })
            }
            power();
        };
        return web.doAjax(root.scenario.deleteById, 'post', params, succCallBack,2);
    });
}